<?php
if (!defined('IS_ADMIN'))
	die('Error 404 : Not found.');

$msg = '';

// Get record
$Qry = 'SELECT *
		FROM categories
		WHERE c_id = ' . $id;
$row = $db->fetchAll($Qry);

if ($submit) {
	$c_name		= isset($_POST['c_name']) ? strval($_POST['c_name']) : $row[0]['c_name'];
	$c_name		= cleaner($c_name, true);

	$c_url		= isset($_POST['c_url']) ? strval($_POST['c_url']) : $row[0]['c_url'];
	$c_url		= remove_unicode($c_url, true);

	if (!$c_url)
		$c_url	= remove_unicode($c_name, true);

	$c_order	= isset($_POST['c_order']) ? intval($_POST['c_order']) : $row[0]['c_order'];

	$data = array(
			'c_name'=>$c_name,
			'c_url'=>$c_url,
			'c_order'=>$c_order
	);

	$condition = 'c_id = ' . $id;

	$result = $db->update('categories', $data, $condition);

	if ($result && $c_url != $row[0]['c_url']) {
		// Find same category
		$Qry = 'SELECT g_id, category
				FROM games
				WHERE category LIKE "%' .  $row[0]['c_url'] . '%"';

		if ($db->numRows($Qry) > 0) {
			$res = $db->fetchAll($Qry);

			foreach ($res as $key=>$value) {
				$str = str_replace($row[0]['c_url'], $c_url, $value['category']);
				// Change new category for all games same category
				$query = 'UPDATE games SET category = "' . $str . '" WHERE g_id = ' . $value['g_id'];

				$db->Query($query);
			}
		}
	}

	$msg = 'Category has been saved.';
}

// assign
$smarty->assign('status', $msg);
$smarty->assign('row', $row);
// SEO
$smarty->assign('title', 'Edit Category - ' . $lang['home_title']);
// Menu
$smarty->assign('is_menu', 'category');
// display theme using smarty
$smarty->display(str_replace(SKIN, 'admin', SMARTY_TEMP) . 'category_edit.tpl');